package servlet;

import model.User;
import service.UserService;
import util.JDBCUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/register.do")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        UserService userService = new UserService();

        // 获取表单参数
        String username = request.getParameter("username"); // 用户名
        int user_type = Integer.parseInt(request.getParameter("user_type")); // 用户类型

        String phone =  request.getParameter("phone"); // 电话号码
        String created_at = null; // 创建时间，假设是从表单中获取的
        String password = request.getParameter("password"); // 密码
        String email = request.getParameter("email"); // 电子邮件

        User user=new User(username,user_type,phone,null,password,email);

        // 检查用户名是否已注册
        if (userService.is_register(username)) {
            // 用户名已存在，重定向到用户名已存在页面
            response.sendRedirect("register/register_exists.jsp");
        } else {
            // 用户名不存在，尝试注册用户
            if (userService.registerUser(user)) {
                // 注册成功，重定向到注册成功页面
                response.sendRedirect("register/register_success.jsp");
            } else {
                // 注册失败，重定向到注册失败页面
                response.sendRedirect("register/register_errorpage.jsp");
            }
        }
    }

    // 检查用户名是否已注册

}
